/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jInternalFrameBancoDados.java
 *
 * Created on 12/12/2011, 21:41:13
 */
package br.com.documentar.view;

import br.com.documentar.interfacee.InterfaceView;
import br.com.documentar.model.ConfigBancoDadosModel;
import br.com.documentar.util.UtilitariosCampos;
import br.com.documentar.util.setFiltroCampo;
import java.awt.HeadlessException;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Willians Santos
 */
public class ConfigBancoDeDadosView extends JFrame implements InterfaceView<br.com.documentar.model.ConfigBancoDadosModel> {

    private final br.com.documentar.controller.ConfigBancoDadosController control = new br.com.documentar.controller.ConfigBancoDadosController();
    private final br.com.documentar.model.ConfigBancoDadosModel model = control.returnModelConfigBancoDados();

    /**
     * Creates new form jInternalFrameBancoDados
     */
    public ConfigBancoDeDadosView() {
        initComponents();
        setLocationRelativeTo(null);
        Start();
    }

    /**
     * Metodo responsável por criar o arquivo e salvar a configuração de acesso
     * ao banco de dados
     */
    private void SaveFileConfig() {
        try {
            File dir1 = new File(control.returnFolderFile());
            File dir2 = new File(dir1.getAbsolutePath());

            //criação da pasta Config caso não exista
            if (!dir2.exists()) {
                dir2.mkdirs();
            }

            //metodo para criar o arquivo
            int a = 0;
            if (control.createFileConfig(model)) {
                a = JOptionPane.showConfirmDialog(rootPane, "Configuração realizada com sucesso.\n"
                        + "Deseja iniciar a aplicação?", "Configuração com sucesso!", JOptionPane.YES_NO_OPTION);
            }
            if (a == 0) {
                setVisible(false);
                LoginView.main();
            } else {
                System.exit(0);
            }

        } catch (EnumConstantNotPresentException ex) {
            Logger.getLogger(ConfigBancoDeDadosView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HeadlessException e) {
            e.getMessage();
        }
    }

    /**
     * Metodo retorno o banco de dados selecionado para se conectar
     *
     * @return Nome do banco de dado selecionado
     */
    private String SelectionDataBase() {
        String opcaoBancoDados = "";
        if (RadioButtonOracle.isSelected()) {
            opcaoBancoDados = "Oracle";
        } else if (RadioButtonFirebird.isSelected()) {
            opcaoBancoDados = "Firebird";
        } else if (RadioButtonMySql.isSelected()) {
            opcaoBancoDados = "MySql";
        } else if (RadioButtonPostGre.isSelected()) {
            opcaoBancoDados = "PostGree";
        } else {
            System.out.println("Erro na montagem do script");
        }
        return opcaoBancoDados;
    }

    public static void main() {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ConfigBancoDeDadosView().setVisible(true);
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooserCaminhoBanco = new javax.swing.JFileChooser();
        jPanelProcessos = new javax.swing.JPanel();
        jProgressBarProcesso = new javax.swing.JProgressBar();
        jLabelProcesso = new javax.swing.JLabel();
        buttonGroup1 = new javax.swing.ButtonGroup();
        panelConfiguracao = new javax.swing.JPanel();
        RadioButtonOracle = new javax.swing.JRadioButton();
        jLabelCaminhoDB = new javax.swing.JLabel();
        ButtonSalvar = new javax.swing.JButton();
        RadioButtonMySql = new javax.swing.JRadioButton();
        RadioButtonPostGre = new javax.swing.JRadioButton();
        jLabelIP1 = new javax.swing.JLabel();
        jLabelPorta = new javax.swing.JLabel();
        RadioButtonFirebird = new javax.swing.JRadioButton();
        ButtonTestarConexao = new javax.swing.JButton();
        textFieldPorta = new javax.swing.JTextField();
        jLabelIP = new javax.swing.JLabel();
        textFieldHost = new javax.swing.JTextField();
        textFieldBanco = new javax.swing.JTextField();

        jFileChooserCaminhoBanco.setCurrentDirectory(new java.io.File("C:\\"));
            jFileChooserCaminhoBanco.setDialogTitle("Selecione o diretório");

            jLabelProcesso.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jLabelProcesso.setText("Processo");

            javax.swing.GroupLayout jPanelProcessosLayout = new javax.swing.GroupLayout(jPanelProcessos);
            jPanelProcessos.setLayout(jPanelProcessosLayout);
            jPanelProcessosLayout.setHorizontalGroup(
                jPanelProcessosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelProcessosLayout.createSequentialGroup()
                    .addGap(37, 37, 37)
                    .addComponent(jProgressBarProcesso, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                    .addGap(27, 27, 27))
                .addComponent(jLabelProcesso, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
            );
            jPanelProcessosLayout.setVerticalGroup(
                jPanelProcessosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanelProcessosLayout.createSequentialGroup()
                    .addComponent(jLabelProcesso, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jProgressBarProcesso, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );

            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("Configuração Banco de Dados");
            setResizable(false);

            buttonGroup1.add(RadioButtonOracle);
            RadioButtonOracle.setText("Oracle");
            RadioButtonOracle.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    RadioButtonOracleMouseClicked(evt);
                }
            });

            jLabelCaminhoDB.setText("Nome do Banco:");

            ButtonSalvar.setText("Salvar");
            ButtonSalvar.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ButtonSalvarActionPerformed(evt);
                }
            });

            buttonGroup1.add(RadioButtonMySql);
            RadioButtonMySql.setText("MySql");
            RadioButtonMySql.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    RadioButtonMySqlMouseClicked(evt);
                }
            });

            buttonGroup1.add(RadioButtonPostGre);
            RadioButtonPostGre.setText("PostGre");
            RadioButtonPostGre.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    RadioButtonPostGreActionPerformed(evt);
                }
            });

            jLabelIP1.setText("IP / Nome Servidor:");

            jLabelPorta.setText("Porta:");

            buttonGroup1.add(RadioButtonFirebird);
            RadioButtonFirebird.setText("Firebird");
            RadioButtonFirebird.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    RadioButtonFirebirdMouseClicked(evt);
                }
            });

            ButtonTestarConexao.setText("Testar");
            ButtonTestarConexao.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ButtonTestarConexaoActionPerformed(evt);
                }
            });

            jLabelIP.setText("Banco de Dados:");

            javax.swing.GroupLayout panelConfiguracaoLayout = new javax.swing.GroupLayout(panelConfiguracao);
            panelConfiguracao.setLayout(panelConfiguracaoLayout);
            panelConfiguracaoLayout.setHorizontalGroup(
                panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panelConfiguracaoLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelConfiguracaoLayout.createSequentialGroup()
                            .addComponent(ButtonTestarConexao)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(ButtonSalvar))
                        .addGroup(panelConfiguracaoLayout.createSequentialGroup()
                            .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabelIP)
                                .addComponent(jLabelCaminhoDB)
                                .addComponent(jLabelPorta)
                                .addComponent(jLabelIP1))
                            .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(panelConfiguracaoLayout.createSequentialGroup()
                                    .addGap(29, 29, 29)
                                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(textFieldPorta)
                                        .addComponent(textFieldBanco)
                                        .addComponent(textFieldHost)))
                                .addGroup(panelConfiguracaoLayout.createSequentialGroup()
                                    .addGap(25, 25, 25)
                                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(RadioButtonOracle)
                                        .addComponent(RadioButtonMySql))
                                    .addGap(32, 32, 32)
                                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(RadioButtonPostGre)
                                        .addComponent(RadioButtonFirebird))
                                    .addGap(0, 53, Short.MAX_VALUE)))))
                    .addContainerGap())
            );
            panelConfiguracaoLayout.setVerticalGroup(
                panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panelConfiguracaoLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(panelConfiguracaoLayout.createSequentialGroup()
                            .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(RadioButtonOracle)
                                .addComponent(RadioButtonFirebird))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(RadioButtonMySql)
                                .addComponent(RadioButtonPostGre))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelConfiguracaoLayout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabelIP)
                            .addGap(26, 26, 26)))
                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabelIP1)
                        .addComponent(textFieldHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabelCaminhoDB)
                        .addComponent(textFieldBanco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabelPorta)
                        .addComponent(textFieldPorta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(panelConfiguracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(ButtonSalvar)
                        .addComponent(ButtonTestarConexao))
                    .addContainerGap())
            );

            panelConfiguracaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {textFieldBanco, textFieldPorta});

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(panelConfiguracao, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(panelConfiguracao, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

private void ButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonSalvarActionPerformed
    if (ValidaCampos()) {
        CarregarVariaveis();
        SaveFileConfig();
    }
}//GEN-LAST:event_ButtonSalvarActionPerformed

    private void ButtonTestarConexaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonTestarConexaoActionPerformed
        TestConnection();
    }//GEN-LAST:event_ButtonTestarConexaoActionPerformed

    private void RadioButtonOracleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RadioButtonOracleMouseClicked
        textFieldBanco.setText("DocumentarSoftware");
        textFieldHost.setText("localhost");
        textFieldPorta.setText("1521");
    }//GEN-LAST:event_RadioButtonOracleMouseClicked

    private void RadioButtonFirebirdMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RadioButtonFirebirdMouseClicked
        textFieldBanco.setText("C:\\Firebird\\DOCUMENTAR.FDB");
        textFieldHost.setText("localhost");
        textFieldPorta.setText("3050");
    }//GEN-LAST:event_RadioButtonFirebirdMouseClicked

    private void RadioButtonMySqlMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RadioButtonMySqlMouseClicked
        textFieldBanco.setText("cloudtfs_cloudConhecimento");
        textFieldHost.setText("208.91.198.197");
        textFieldPorta.setText("3306");
    }//GEN-LAST:event_RadioButtonMySqlMouseClicked

    private void RadioButtonPostGreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RadioButtonPostGreActionPerformed
        textFieldBanco.setText("DocumentarSoftware");
        textFieldHost.setText("localhost");
        textFieldPorta.setText("5432");
    }//GEN-LAST:event_RadioButtonPostGreActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonSalvar;
    private javax.swing.JButton ButtonTestarConexao;
    private javax.swing.JRadioButton RadioButtonFirebird;
    private javax.swing.JRadioButton RadioButtonMySql;
    private javax.swing.JRadioButton RadioButtonOracle;
    private javax.swing.JRadioButton RadioButtonPostGre;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JFileChooser jFileChooserCaminhoBanco;
    private javax.swing.JLabel jLabelCaminhoDB;
    private javax.swing.JLabel jLabelIP;
    private javax.swing.JLabel jLabelIP1;
    private javax.swing.JLabel jLabelPorta;
    private javax.swing.JLabel jLabelProcesso;
    private javax.swing.JPanel jPanelProcessos;
    private javax.swing.JProgressBar jProgressBarProcesso;
    private javax.swing.JPanel panelConfiguracao;
    private javax.swing.JTextField textFieldBanco;
    private javax.swing.JTextField textFieldHost;
    private javax.swing.JTextField textFieldPorta;
    // End of variables declaration//GEN-END:variables

    @Override
    public void CarregarEditarDados() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void CarregarNovoDados() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void CarregarExcluirDados() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void CancelarOperacao() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void CarregarVariaveis() {
        model.setOpcaoBancoDados(SelectionDataBase());
        model.setBanco(textFieldBanco.getText());
        model.setHost(textFieldHost.getText());
        model.setPorta(textFieldPorta.getText());
    }

    @Override
    public void GravarDados() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void LimparCampos() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void ProximaAba(String Movimento) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void TamanhoColunaTable() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void Consultar() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void CommitCampos() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void InicializarListener() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void TestConnection() {
        if (ValidaCampos()) {
            CarregarVariaveis();
            if (control.TestConnectionBancoDados(model)) {
                JOptionPane.showMessageDialog(rootPane, "Conexão estabelecida com sucesso!");
            } else {
                JOptionPane.showMessageDialog(rootPane, "Ops!!! Não foi possível conectar no server!!!");
            }
        }
    }

    @Override
    public void Start() {
        setFiltroCampo();
    }

    @Override
    public boolean ValidaCampos() {
        if (SelectionDataBase().equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Nenhuma opção de banco de dados foi selecionada.");
            return false;
        }
        return UtilitariosCampos.getValidarCampos(panelConfiguracao);
    }

    @Override
    public void CarregarDadosComboBox(ConfigBancoDadosModel model, String actionScript) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void setFiltroCampo() {
        textFieldHost.setDocument(new setFiltroCampo(50, "HostIP"));
        textFieldBanco.setDocument(new setFiltroCampo(100, "Texto", 'P'));
        textFieldPorta.setDocument(new setFiltroCampo(20, "NumeroInteiro"));
    }

}
